package org.theSeed.base.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;
import org.theSeed.base.pojo.dto.CommonKeyValue;

import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt 工具
 */
public class JwtUtil {
    // 生成JWT
    public static String generateToken(Key key, String userKey, long timeMillis) {

        return Jwts.builder()
                .setSubject(userKey)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + timeMillis)) // 过期时间1小时
                .signWith(key) // 签名
                .compact();
    }
 
    // 解析JWT
    public static Claims parseToken(Key key,String token) throws JwtException {
        try {
            JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(key);
            return jwtParserBuilder
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {
            // 捕获解析异常，抛出一个自定义的异常或返回null
            throw new JwtException("Invalid token: " + e.getMessage(), e);
        }
    }
 
    // 检查JWT是否有效
    public static boolean isTokenExpired(Key key,String token) {
        try {
            Claims claims = parseToken(key,token);
            return claims.getExpiration().before(new Date());
        } catch (JwtException e) {
            // 解析失败，视为Token无效
            return true;
        }
    }

    // 获取用户id
    public static Object getClaims(Key key,String token) {
        try {
            Claims claims = parseToken(key,token);
            return claims != null ? claims.get("userId", Integer.class) : null;
        } catch (JwtException e) {
            // Token无效，返回null或可以选择抛出异常
            return null;
        }
    }


    /**
     * 密钥测试案例
     * @param args
     */
    public static void main(String[] args) {
        CommonKeyValue<PublicKey, PrivateKey> keyPair = RsaUtil.createKeyPair("RSA",2048);
        String token = generateToken(keyPair.getValue(), "123456", 1000000);

        System.out.println("token信息为"+token);

        Claims claims1 = parseToken(keyPair.getKey(), token);
        System.out.println(JSONUtil.toJsonStr(claims1));

        System.out.println("公钥信息为 "+ Base64.encodeBase64String(keyPair.getKey().getEncoded()));
        System.out.println("私钥信息为 "+ Base64.encodeBase64String(keyPair.getValue().getEncoded()));
    }
}